package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class Myfilter
 */
@WebFilter("/*")
public class Myfilter implements Filter {

    /**
     * Default constructor. 
     */
    public Myfilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		System.out.println("check...");
		request.setCharacterEncoding("utf-8");
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;

		String requestPath = httpRequest.getServletPath();
		System.out.println("requestPath:" + requestPath);

		
		if(!(requestPath.endsWith(".css")||requestPath.endsWith(".js")||requestPath.endsWith(".map")||requestPath.contains("Login")||requestPath.contains("Loginout")||requestPath.contains("bootstrap"))) {
			String isok=(String) httpRequest.getSession().getAttribute("isok");
			System.out.println("isok:"+isok);
			if(isok==null) {
				//未登录
				System.out.println("跳转到登录页面");
				//计算当前路径
		
				String path = httpRequest.getContextPath();
				String basePath=httpRequest.getScheme()+"://"+httpRequest.getServerName()+":"+httpRequest.getServerPort()+path+"/";
				httpResponse.sendRedirect(basePath+ "Login.jsp");
		        return;
			}
			
		}
		
		chain.doFilter(request, response);
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
